package collect

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

// extractPaths 分割 *路径
func extractPaths(pathStr string) (beforeStar string, betweenStars string, err error) {
	pathStr = filepath.FromSlash(pathStr)
	parts := strings.Split(pathStr, "*")
	if len(parts) < 2 {
		err = fmt.Errorf("path does not contain enough '*' characters")
		return
	}
	beforeStar = strings.Join(parts[:1], "*")
	if len(parts) >= 3 {
		betweenStars = strings.Join(parts[1:2], "*")
	}
	beforeStar = filepath.ToSlash(beforeStar)
	if betweenStars != "" {
		betweenStars = filepath.ToSlash(betweenStars)
	}
	beforeStar = filepath.Dir(beforeStar)
	betweenStars = filepath.Dir(betweenStars)
	return
}

// extractFileExtension 获得文件的类型
func extractFileExtension(pathStr string) string {
	lastDotIndex := strings.LastIndex(pathStr, ".")
	if lastDotIndex == -1 {
		return ""
	}
	return pathStr[lastDotIndex+1:]
}

// checkPathIsDir 判断路径是文件还是目录
func checkPathIsDir(path string) (b bool, err error) {
	fileInfo, err := os.Stat(path)
	if err != nil {
		//fmt.Println("Error:", err)
		return
	}
	return fileInfo.IsDir(), err
}
func checkPath(path string) bool {
	now := time.Now()
	yesterday := now.AddDate(0, 0, -1)
	todayStr := now.Format(time.DateOnly)
	yesterdayStr := yesterday.Format(time.DateOnly)
	// 编译正则表达式，用于匹配日期
	re := regexp.MustCompile(`tqlog-(\d{4}-\d{2}-\d{2})-.*\.log`)
	// 遍历日志文件名，检查是否匹配今天或昨天的日期
	matches := re.FindStringSubmatch(path)
	if len(matches) > 1 {
		// 提取日期部分
		dateStr := matches[1]
		if dateStr == todayStr || dateStr == yesterdayStr {
			return true
		}
	}
	return false
}
func EnsureDir(dir string) error {
	// 确保目录存在
	if err := os.MkdirAll(dir, 0755); err != nil {
		// 如果错误不是“文件已存在”，则返回错误
		if !os.IsExist(err) {
			return err
		}
	}
	return nil
}
